<template>
  <div class="page-container">
    <div class="content-wrapper">
      <!-- 标题区域 -->
      <div class="page-title">
        <div class="title-indicator"></div>
        <h2 style="color: #4b4b4b">居民管理</h2>
      </div>

      <div class="filter-container">
        <div class="filter-row">
          <div class="filter-item">
            <span class="filter-label">签约状态</span>
            <el-select v-model="selectedStatus" placeholder="请选择" class="filter-select" @change="initData" clearable>
              <el-option v-for="s in status" :key="s.name" :label="s.name" :value="s.name"></el-option>
            </el-select>
          </div>
          <div class="filter-item">
            <span class="filter-label">签约机构</span>
            <el-select v-model="selectedInstitution" placeholder="请选择" class="filter-select" @change="initData" clearable value-key="name">
              <el-option v-for="i in institutions" :key="`inst-${i.id}-${i.name}`" :label="i.name" :value="i.name"></el-option>
            </el-select>
          </div>
          <div class="filter-item">
            <span class="filter-label">医生团队</span>
            <el-select v-model="selectedTeam" placeholder="请选择" class="filter-select" @change="initData" clearable value-key="name">
              <el-option v-for="t in teams" :key="`team-${t.id}-${t.name}`" :label="t.name" :value="t.name"></el-option>
            </el-select>
          </div>
        </div>
        <div class="filter-row filter-row-bottom">
          <div class="filter-row-left">
            <div class="filter-item">
              <span class="filter-label">服务包</span>
              <el-select v-model="selectedPackage" placeholder="请选择" class="filter-select" @change="initData" clearable value-key="name">
                <el-option v-for="p in packages" :key="`pkg-${p.id}-${p.name}`" :label="p.name" :value="p.name"></el-option>
              </el-select>
            </div>
            <div class="filter-item">
              <span class="filter-label">居民标签</span>
              <el-select v-model="selectedTags" placeholder="请选择" class="filter-select" @change="initData" clearable>
                <el-option v-for="t in tags" :key="t.name" :label="t.name" :value="t.name"></el-option>
              </el-select>
            </div>
            <div class="filter-item search-item">
              <el-input
                v-model="searchText"
                placeholder="请输入关键字"
                class="search-input"
                :suffix-icon="Search"
                @change="initData"
                clearable
              ></el-input>
            </div>
          </div>
          <div class="filter-row-right">
            <el-button type="primary" @click="goToCreatePage()" class="primary-btn">新增居民档案</el-button>
            <el-button @click="exportResidents()" class="export-btn">导出</el-button>
            <el-button @click="exportQy()" class="export-btn">签约</el-button>
            <el-button @click="exportMap()" class="export-btn">地图</el-button>
            <el-button @click="exportFw()" class="export-btn">服务</el-button>
            <el-button @click="exportIndex()" class="export-btn">首页</el-button>
            <div class="view-toggle">
              <el-tooltip content="表格视图" placement="top">
                <div
                  class="toggle-btn"
                  :class="{ 'active': viewMode === 'table' }"
                  @click="switchViewMode('table')"
                >
                  <svg class="toggle-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.9 20.1 3 19 3ZM5 5H11V11H5V5ZM5 13H11V19H5V13ZM19 19H13V13H19V19ZM19 11H13V5H19V11Z" fill="currentColor"/>
                  </svg>
                </div>
              </el-tooltip>
              <el-tooltip content="卡片视图" placement="top">
                <div
                  class="toggle-btn"
                  :class="{ 'active': viewMode === 'card' }"
                  @click="switchViewMode('card')"
                >
                  <svg class="toggle-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M4 11H9V5H4V11ZM4 18H9V12H4V18ZM10 18H15V12H10V18ZM16 18H21V12H16V18ZM10 11H15V5H10V11ZM16 5V11H21V5H16Z" fill="currentColor"/>
                  </svg>
                </div>
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>

      <!-- 表格视图 -->
      <div v-if="viewMode === 'table'" class="table-view">
        <el-table :data="residents" style="width: 100%" stripe @selection-change="handleSelectionChange">
          <el-table-column type="selection" :selectable="selectable" width="55"></el-table-column>
          <el-table-column prop="id" label="编号" width="100"></el-table-column>
          <el-table-column label="姓名" width="150">
            <template #default="{ row }">
              <div class="name-cell">
                <img
                    class="avatar"
                    :src="'http://localhost:8080/images/' + row.avatar"
                    alt="头像"
                />
                <span class="name-text">{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="idCard" label="身份证" width="220"></el-table-column>
          <el-table-column prop="phone" label="手机号" width="140"></el-table-column>
          <el-table-column label="签约状态" width="100">
            <template #default=" { row }">
              <span class="table-sign-status" :style="{ color: statusColorMap[row.statusColor] || '#606266' }">
                {{ row.statusName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="居民标签" idth="240">
            <template #default="{ row }">
              <div class="tag-table-container" style="display: flex; flex-wrap: wrap;">
                <el-tag
                    v-for="(tag, index) in row.tag"
                    :key="index"
                    :type="getRandomTagType()"
                    class="tag-item"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="openResidentInfo(row)">查看详情</el-button>
              <el-button type="primary" size="small" @click="goToInfoPage(row)">编辑</el-button>
              <el-button type="primary" size="small">添加服务</el-button>
              <el-button type="danger" size="small" @click="deleteResident(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-else class="card-container">
        <div class="card-row" >
          <div class="card-col" v-for="c in residents" :key="c.id" @click="openResidentInfo(c)">
            <div class="resident-card">
              <div class="avatar-container" >
                <img :src="'http://localhost:8080/images/' + c.avatar" alt="居民头像">
              </div>
              <div class="resident-info">
                <div class="resident-name">{{ c.name }}</div>
                {{ c.age }}岁
                <el-icon class="gender-icon" v-if="c.gender === '男'"><Male /></el-icon>
                <el-icon class="gender-icon" v-else><Female /></el-icon>
              </div>
<!--              <div class="status-signed">{{ c.status }}</div>-->
              <div class="status-signed">
                {{ c.statusName }}
              </div>
              <div class="tag-container" style="display: flex; flex-wrap: wrap;">
                <el-tag
                    v-for="(tag, index) in c.tag"
                    :key="index"
                    :type="getRandomTagType()"
                    class="tag-item"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="pagination-container">
        <div class="pagination-info">
          <el-pagination
              v-model:current-page="pageNum"
              v-model:page-size="pageSize"
              :page-sizes="[10, 15, 20, 25, 30]"
              layout="total, sizes, prev, pager, next, jumper"
              v-model:total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>

import { ref, onMounted } from 'vue'
import { Search, Male, Female, Setting, DataAnalysis, Download, Plus } from '@element-plus/icons-vue'
import { generateAvatar } from '../utils/avatar.js'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from "vue-router";
import axios from "axios";

const router = useRouter()
const tagTypes = ['success', 'info', 'warning', 'danger']

const statusColorMap = {
  success: '#67C23A', // green
  warning: '#E6A23C', // orange
  danger: '#F56C6C',  // red
  info: '#909399'     // gray
}

const getRandomTagType = () => {
  const index = Math.floor(Math.random() * tagTypes.length)
  return tagTypes[index]
}

const exportQy = () => {
  router.push('/main/contract_wait')
}

const exportMap = () => {
  router.push('/main/resident-map')
}

const exportFw = () => {
  router.push('/main/index0')
}

const exportIndex = () => {
  router.push('/main/dashboard')
}

const openInst = () => {
  router.push('/main/InstitutionManagement')
}

const openDashboard = () => {
  router.push('/main/dashboard')
}

const goToCreatePage = () => {
  router.push('/main/ResidentCreate')
}

const goToInfoPage = (row) => {
  router.push({ name: 'ResidentInfo', query: { id: row.id } })
}

const openResidentInfo = (val) => {
  console.log('openResidentInfo', val)
  router.push({name: 'ResidentDetail', query: {id: val.id}})
}

const handleSelectionChange = ref()

const selectable = ref()

// 视图模式（表格/卡片）
const viewMode = ref('card')

// 表格数据
const residents = ref([])

const searchText = ref('')

const selectedTags = ref('')

const selectedStatus = ref('')

const selectedInstitution = ref('')

const selectedTeam = ref('')

const selectedPackage = ref('')

const minAge = ref('')
const maxAge = ref('')

const openRole = () => {
  router.push('/main/RoleManagement')
}

// 表格展示
const initData = async () => {
  const query = {
    tagName: selectedTags.value,
    statusName: selectedStatus.value,
    keyword: searchText.value,
    institutionName: selectedInstitution.value,
    teamName: selectedTeam.value,
    packageName: selectedPackage.value,
    minAge: minAge.value || null,
    maxAge: maxAge.value || null
  }

  const resp = await axios.post(`/resident/getResident/${pageNum.value}/${pageSize.value}`, query)
  const result = resp.data.data

  if (!result || result.length === 0) {
    ElMessage.info("未搜索到相关结果，显示全部数据")

    selectedTags.value = null
    selectedStatus.value = null
    selectedInstitution.value = null
    selectedTeam.value = null
    selectedPackage.value = null
    searchText.value = ''
    minAge.value = ''
    maxAge.value = ''

    const respAll = await axios.post(`/resident/getResident/${pageNum.value}/${pageSize.value}`, {
      tagName: null,
      statusName: null,
      institutionName: null,
      teamName: null,
      packageName: null,
      keyword: null,
      minAge: null,
      maxAge: null
    })
    residents.value = respAll.data.data
    total.value = respAll.data.total
  } else {
    residents.value = result
    total.value = resp.data.total
  }
}

// 切换视图模式
const switchViewMode = (mode) => {
  viewMode.value = mode
}

const deleteResident = (row) => {
  axios.delete(`/resident/deleteResident/${row.id}`).then(resp => {
    console.log(row.id)
      ElMessage.success(resp.data)
      initData()
  })
}

// 分页
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(12);
const handleSizeChange = (val) => {
  pageSize.value = val;
  initData();
}

const handleCurrentChange = (val) => {
  pageNum.value = val;
  initData();
}
const tags = ref('')

const status = ref('')

const institutions = ref([])

const teams = ref([])

const packages = ref([])

const getAllTag = () => {
  axios.get("/tag/getAllTag").then(resp => {
    tags.value = resp.data;
  })
}

const getAllStatus = () => {
  axios.get("/Status/getAllStatus").then(resp => {
    status.value = resp.data;
  })
}

const getAllInstitutions = () => {
  axios.get("/resident/getAllInstitutions").then(resp => {
    // 前端去重保护
    const uniqueInstitutions = [];
    const nameSet = new Set();
    resp.data.forEach(item => {
      if (!nameSet.has(item.name)) {
        nameSet.add(item.name);
        uniqueInstitutions.push(item);
      }
    });
    institutions.value = uniqueInstitutions;
  }).catch(() => {
    // 如果API调用失败，使用默认数据
    institutions.value = [
      { id: 1, name: "朝阳社区卫生服务中心" },
      { id: 2, name: "海淀区中心医院" }
    ];
  })
}

const getAllTeams = () => {
  axios.get("/resident/getAllTeams").then(resp => {
    // 前端去重保护
    const uniqueTeams = [];
    const nameSet = new Set();
    resp.data.forEach(item => {
      if (!nameSet.has(item.name)) {
        nameSet.add(item.name);
        uniqueTeams.push(item);
      }
    });
    teams.value = uniqueTeams;
  }).catch(() => {
    // 如果API调用失败，使用默认数据
    teams.value = [
      { id: 1, name: "朝阳第一家庭医生团队" },
      { id: 2, name: "海淀精英医疗团队" }
    ];
  })
}

const getAllPackages = () => {
  axios.get("/resident/getAllPackages").then(resp => {
    // 前端去重保护
    const uniquePackages = [];
    const nameSet = new Set();
    resp.data.forEach(item => {
      if (!nameSet.has(item.name)) {
        nameSet.add(item.name);
        uniquePackages.push(item);
      }
    });
    packages.value = uniquePackages;
  }).catch(() => {
    // 如果API调用失败，使用默认数据
    packages.value = [
      { id: 1, name: "基础医疗服务包" },
      { id: 2, name: "慢病管理服务包" }
    ];
  })
}

const getTagsAndStatus =() => {
  getAllTag();
  getAllStatus();
  getAllInstitutions();
  getAllTeams();
  getAllPackages();
}

// 导出居民数据
const exportResidents = async () => {
  try {
    ElMessage.info('正在准备导出数据...')

    const response = await axios.get('/resident/export', {
      responseType: 'blob', // 重要：指定响应类型为blob
    })

    // 创建下载链接
    const blob = new Blob([response.data], { type: 'text/csv;charset=utf-8' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url

    // 生成文件名（包含当前日期）
    const now = new Date()
    const dateStr = now.getFullYear() +
                   String(now.getMonth() + 1).padStart(2, '0') +
                   String(now.getDate()).padStart(2, '0')
    link.download = `居民数据导出_${dateStr}.csv`

    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功！')

  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 头像URL
const avatarUrl = ref('')

onMounted(() => {
  initData();
  getTagsAndStatus();
  avatarUrl.value = generateAvatar()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.content-wrapper {
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.page-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.title-indicator {
  width: 4px;
  height: 20px;
  background-color: #1890ff;
  margin-right: 8px;
}

.filter-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 24px 24px 12px 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 12px;
}

.filter-row-bottom {
  margin-bottom: 0;
  justify-content: space-between;
}

.filter-row-left {
  display: flex;
  align-items: center;
  gap: 24px;
}

.filter-row-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-item {
  min-width: 220px;
  flex: none;
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  min-width: 60px;
}

.filter-select {
  min-width: 120px;
  width: 160px;
  max-width: 200px;
}

.search-item {
  min-width: 260px;
}

.search-input {
  min-width: 180px;
  width: 220px;
  max-width: 260px;
}

.primary-btn {
  padding: 8px 20px;
}

.export-btn {
  border: 1px solid #dcdfe6;
  color: #606266;
  padding: 8px 16px;
}

.view-toggle {
  display: flex;
  gap: 2px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 2px;
  margin-left: 8px;
}

.toggle-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 3px;
  color: #606266;
}

.toggle-btn:hover {
  background-color: #f5f7fa;
}

.toggle-btn.active {
  background-color: #409eff;
  color: white;
}

.toggle-icon {
  width: 16px;
  height: 16px;
}

/* 操作按钮组 */
.action-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
}

.action-buttons .el-button {
  border-radius: 4px;
}

.action-buttons .el-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
}

.action-buttons .el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

/* 表格视图样式 */
.table-view {
  margin-bottom: 20px;
}

.table-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
}

.table-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.tag-container-table {
  display: flex;
  gap: 5px;
}

/* 卡片视图样式 */
.card-container {
  width: 100%;
}

.card-row {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  padding: 10px;
}

.card-col {
  width: 100%;
}

.resident-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 1;
  position: relative;
  overflow: hidden;
}

.resident-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at center, rgba(24, 144, 255, 0.1) 0%, rgba(24, 144, 255, 0) 70%);
  opacity: 0;
  transform: scale(0.8);
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  z-index: -1;
}

.resident-card:hover {
  box-shadow: 0 8px 25px 0 rgba(0, 0, 0, 0.15);
  transform: translateY(-6px) scale(1.02);
  z-index: 2;
}

.resident-card:hover::before {
  opacity: 1;
  transform: scale(1.5);
}

.avatar-container {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 10px;
  background-color: #f0f0f0;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.resident-card:hover .avatar-container {
  border-color: rgba(24, 144, 255, 0.3);
  transform: scale(1.05);
}

.avatar-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.resident-name {
  color: #383838;
  font-size: 18px;
  font-weight: 500;
  margin-right: 4px;
  margin-bottom: 4px;
  transition: all 0.3s ease;
}

.resident-card:hover .resident-name {
  color: #1890ff;
}

.resident-info {
  color: #999;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.gender-icon {
  margin-left: 4px;
  color: #999;
}

.status-signed {
  background-color: rgba(40, 208, 148, 1);
  color: white;
  border-radius: 15px;
  padding: 2px 10px;
  font-size: 12px;
  display: inline-block;
  margin: 8px 0;
  transition: all 0.3s ease;
}

.resident-card:hover .status-signed {
  background-color: #00a99d;
  box-shadow: 0 2px 8px rgba(0, 169, 157, 0.3);
}

.tag-container {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 10px;
  transition: all 0.3s ease;
}

.tag-table-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 10px;
  transition: all 0.3s ease;
}

.resident-card:hover .tag-container {
  transform: translateY(2px);
}

.tag-hypertension {
  background-color: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
  border-color: transparent;
  transition: all 0.3s ease;
}

.resident-card:hover .tag-hypertension {
  background-color: rgba(245, 108, 108, 0.2);
}

.tag-heart {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
  border-color: transparent;
  transition: all 0.3s ease;
}

.resident-card:hover .tag-heart {
  background-color: rgba(64, 158, 255, 0.2);
}

.tag-diabetes {
  background-color: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
  border-color: transparent;
  transition: all 0.3s ease;
}

.resident-card:hover .tag-diabetes {
  background-color: rgba(230, 162, 60, 0.2);
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
}

.pagination-info {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
}

.pagination-size-select {
  width: 100px;
  margin-left: 10px;
}

.pagination-jumper {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
}

.page-jump-input {
  width: 50px;
  margin: 0 5px;
}

/* 响应式布局调整 */
@media screen and (max-width: 1600px) {
  .card-row {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  }
}

@media screen and (max-width: 1200px) {
  .card-row {
    grid-template-columns: repeat(2, 1fr);
  }
  .filter-row {
    flex-wrap: wrap;
  }
  .filter-item {
    flex: 1 1 45%;
    min-width: 140px;
    max-width: 100%;
  }
  .filter-actions {
    margin-left: 0;
    justify-content: flex-start;
  }
  .filter-select {
    width: 120px;
  }
  .search-input {
    width: 200px;
  }
}

@media screen and (max-width: 700px) {
  .card-row {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
  .filter-item {
    flex: 1 1 100%;
    min-width: 100px;
  }
  .search-input, .filter-select {
    min-width: 100px;
    max-width: 100%;
  }
}

.name-cell {
  display: flex;
  align-items: center;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.2);
}

.name-text {
  font-weight: 500;
}

.table-sign-status {
  font-size: 13px;
  font-family: 'PingFangSC-Regular', 'PingFang SC',serif;
}

.ageInput {
  width: 80px;
}
</style>
